//
//  MaintenanceGuideView.swift
//  koolcar
//
//  Created by xiantian on 2023/10/25.
//

import UIKit
import FSCalendar
class MaintenanceGuideView: UIView {
    var calendarView: FSCalendar!
    var titleLab: UILabel!
    var arrowBtn: UIButton!
    
    var showAllBtn: UIButton = {
        let tempBtn = UIButton()
        tempBtn.isUserInteractionEnabled = false
        tempBtn.setup_image(image: UIImage.init(named: "maintence_arrow_down"))
        return tempBtn
    }()
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.init(hex: 0x000000, alpha: 0.7)
        calendarView = FSCalendar.init(frame: CGRect.init(x: 0, y: NavBarHight - 40, width: kScreenWidth, height: 358))
        self.calendarView.scope = .week
        self.calendarView.headerHeight = 0
        self.calendarView.backgroundColor = .white
        self.calendarView.appearance.borderRadius = 0
        self.calendarView.appearance.todayColor = Theme.mainColorHighLightColor
        self.calendarView.appearance.selectionColor = UIColor.init(hex: 0x71D883, alpha: 0.3)
        self.calendarView.appearance.titleSelectionColor = Theme.titleLabColor
        self.calendarView.appearance.titleTodayColor = Theme.titleLabColor
        self.calendarView.appearance.headerTitleColor = Theme.titleLabColor
        self.calendarView.appearance.weekdayTextColor = Theme.placeholderColor
        self.calendarView.appearance.weekdayFont = UIFont.init(name: Theme.PingFangSCRegular, size: 12)
        self.calendarView.appearance.titleFont = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        self.calendarView.appearance.headerDateFormat = "yyyy-MM"
        self.calendarView.appearance.todayColor = Theme.whiteColor
        var tempLocal = "zh-CN"
        let curLan = XTManageCenter.getAppleLanguages()
        switch curLan {
        case AppLanguage.english.rawValue:
            tempLocal = "en"
        case AppLanguage.chinese_hk.rawValue:
            tempLocal = "zh-HK"
        default:
            ()
        }
        self.calendarView.locale = Locale.init(identifier: tempLocal)
        self.addSubview(calendarView)
        
        self.addSubview(showAllBtn)
        
        titleLab = UILabel()
        titleLab.textColor = Theme.whiteColor
        titleLab.backgroundColor = UIColor.clear
        titleLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        titleLab.numberOfLines = 1
        titleLab.lineBreakMode = .byTruncatingTail
        titleLab.textAlignment = .center
        titleLab.text = String(format: MMLocalizedString("mainten_guide_tip", comment: "向下拖动选择更多日期，可预约未来%@天服务"), "90")
        self.addSubview(titleLab)
        
        let tap = UITapGestureRecognizer.init {[weak self] _ in
            self?.handleDismiss()
        }
        tap.numberOfTapsRequired = 1
        self.addGestureRecognizer(tap)
        self.addSnpLayout()
        self.fetchAvailabilityList()
    }
    
    private func addSnpLayout(){
        self.calendarView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.width.equalTo(kScreenWidth)
            make.top.equalTo(NavBarHight - 40)
            make.height.equalTo(358)
        }
        showAllBtn.snp.makeConstraints { make in
            make.top.equalTo(calendarView.snp.bottom).offset(-10)
            make.width.equalTo(20)
            make.height.equalTo(20)
            make.centerX.equalTo(kScreenWidth/2)
        }
        
        titleLab.sizeToFit()
        titleLab.snp.makeConstraints { make in
            make.centerX.equalTo(showAllBtn.snp.centerX)
            make.height.greaterThanOrEqualTo(20)
            make.top.equalTo(showAllBtn.snp.bottom).offset(20)
        }
        
        self.layoutIfNeeded()
        self.calendarView.scope = .week
        self.calendarView.snp.updateConstraints { make in
            make.height.equalTo(88)
            make.top.equalTo(NavBarHight)
        }
        self.updateConstraints()
    }
    
    private func handleDismiss(){
        XTManageCenter.setLocalDataString(aKey: UtilCenter.kFirstLoadMaintence, aValue: "1")
        UIView.animate(withDuration: 0.8, delay: 0, options: UIViewAnimationOptions.curveLinear) {
            self.frame.size.height = self.calendarView.frame.size.height
            self.frame.origin.y = NavBarHight
            self.calendarView.snp.updateConstraints { make in
                make.top.equalTo(0)
            }
            self.layoutIfNeeded()
        } completion: { flag in
            if flag {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
                    self.removeFromSuperview()
                })
            }
        }
        
    }
    
    ///当月日历预约数据展示
    private func fetchAvailabilityList(){
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.bookingAvailabilityList, objectType: CalenderAvailabilityResModel.self) { data in
            let resultObj = data as! CalenderAvailabilityResModel
            if resultObj.code == "1" {
                let totalDay = resultObj.extData?.bookDay ?? 30
                self.titleLab.text = String(format: MMLocalizedString("mainten_guide_tip", comment: "向下拖动选择更多日期，可预约未来%@天服务"), "\(totalDay)")
            }
        } error: { err in
            self.makeToast(message: err?.domain ?? "")
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
